/*
 * Created on Feb 15, 2005
 * Created by dfhuynh
 */
package it.okkam.longwell.ui.command;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;

import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.impl.PropertyImpl;
import com.hp.hpl.jena.tdb.TDBFactory;
import com.hp.hpl.jena.vocabulary.DC;

import edu.mit.simile.longwell.LongwellServer;
import edu.mit.simile.longwell.LongwellServlet;
import edu.mit.simile.longwell.schema.IStructuredSchema;
import edu.mit.simile.longwell.ui.Facade;
import edu.mit.simile.longwell.ui.FlairMessage;
import edu.mit.simile.longwell.ui.FlairStructuredModel;
import edu.mit.simile.longwell.ui.InjectionManager;
import edu.mit.simile.longwell.ui.command.CommandBase;

/**
 * @author dfhuynh
 */
public class SelectGraphsCommand extends CommandBase {
	final static private Logger s_logger = Logger.getLogger(SelectGraphsCommand.class);
	static private HashMap<String, Dataset> m_graphsByDataset;
	static HashMap<String, HashMap<String, Dataset>> hash = new HashMap<String, HashMap<String,Dataset>>();
	final protected String m_template;
	private File[] m_filesComuni;
	HashMap<String, String> imagesList = new HashMap<String, String>();
	/**
	 * @param injectionManager
	 */
	public SelectGraphsCommand(InjectionManager injectionManager, String template) {
		super(injectionManager);
		m_template = template;

	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.flair.IFlairCommand#execute(edu.mit.simile.flair.FlairMessage)
	 */
	public void execute(FlairMessage msg) throws ServletException {
		String [] listaComuni = SetDatasetCommand.getListaComuni();
//		String[] values = msg.m_request.getParameterValues("listaComuni");

		for (int i=0; i<listaComuni.length;i++){			
			s_logger.info("Select grafi for comune=" +listaComuni[i]);
		}
		
		try {
			VelocityContext vcContext = createContext(msg);
			HttpSession session = msg.m_request.getSession();
			String sessionId = session.getId();
			//vcContext.put("graphs", getGraphs(msg,(String[]) session.getAttribute(sessionId)));
			vcContext.put("graphs", getGraphsFromDefaultModel(msg,(String[]) session.getAttribute(sessionId)));
			vcContext.put("imagesList",imagesList);
			vcContext.put("sessionId", msg.m_request.getSession().getId());
			msg.m_ve.mergeTemplate(
				m_template,
				vcContext,
				msg.m_response.getWriter());
		} catch (Exception e) {
			s_logger.error(e);
			e.printStackTrace();
		}
	}
	
	protected Set getGraphs(FlairMessage msg,String[] listaComuni) {

		SortedSet sGraphs = new TreeSet();
		
		m_graphsByDataset = new HashMap<String, Dataset>();
		for (int i = 0; i < listaComuni.length; i++) {
			File file = new File(listaComuni[i]+"-assembler.ttl");
			String assemblerFile = file.getName() ;    
			s_logger.info("Loading assembler : "+LongwellServlet.getAssemblerDirectory()+"/"+assemblerFile);
			Dataset ds = TDBFactory.assembleDataset(LongwellServlet.getAssemblerDirectory()+"/"+assemblerFile);	
			
			Iterator<String> graphNames = ds.listNames();
			if(graphNames!=null){
				while (graphNames.hasNext()) {
				    String graphName = graphNames.next();
				    //System.out.println(graphName);
				    m_graphsByDataset.put(graphName, ds);
				    sGraphs.add(graphName);
				}
			}
			else{
				m_graphsByDataset.put("NOGRAPHS", ds);
			}
		}
		hash.put(msg.m_request.getSession().getId(), m_graphsByDataset);
		return sGraphs;
	}
	
	
	protected HashMap<String, HashMap<String,String>> getGraphsFromDefaultModel(FlairMessage msg,String[] listaComuni) {
		SortedSet sGraphs = new TreeSet();
		HashMap<String, HashMap<String, String>> graphsList = new HashMap<String, HashMap<String,String>>();
		
		m_graphsByDataset = new HashMap<String, Dataset>();
		Model defaultModel=null;
		
		for (int i = 0; i < listaComuni.length; i++) {
			File file = new File(listaComuni[i]+"-assembler.ttl");
			String assemblerFile = file.getName() ;    
			s_logger.info("Loading assembler : "+LongwellServlet.getAssemblerDirectory()+"/"+assemblerFile);
			Dataset ds = TDBFactory.assembleDataset(LongwellServlet.getAssemblerDirectory()+"/"+assemblerFile);	
			//defaultModel = ds.getDefaultModel();
			defaultModel = ds.getNamedModel("http://www.provincia.tn.it/bcc/resource/"+listaComuni[i]);
			
			Iterator<Statement> statements = defaultModel.listStatements(null, DC.title,(RDFNode) null);
			//for each flow (anagrafe, catasto, titolarita)
			while(statements.hasNext()){
				HashMap<String, String> graphsWithLabel = new HashMap<String, String>();
				Statement statement = statements.next();
				String titleFlow = statement.getObject().toString();
				
				Resource uriFlow = statement.getSubject();
				
				Iterator<Statement> images = defaultModel.listStatements(uriFlow, DC.identifier,(RDFNode) null);
				String image = "";
				while(images.hasNext()){
					image = images.next().getObject().toString();
				}
				Property hasPart = new PropertyImpl("http://purl.org/dc/elements/1.1/hasPart");
				
				Iterator<Statement> graphs = defaultModel.listStatements(uriFlow,hasPart,(RDFNode)null);
				//for each graph
				while(graphs.hasNext()){
					Statement graph = graphs.next();
					Property issued = new PropertyImpl("http://purl.org/dc/elements/1.1/issued");
					Resource graphName = (Resource) graph.getObject();
					Iterator<Statement> graphLabel = defaultModel.listStatements(graphName,issued,(RDFNode)null);
					//read label
					while(graphLabel.hasNext()){
						String label = graphLabel.next().getObject().toString();
						graphsWithLabel.put(graphName.toString(), label);
					}
				}
				graphsList.put(titleFlow, graphsWithLabel);
				if(image.length()>0){
					imagesList.put(titleFlow,image);
				}
			}
			
			
			Iterator<String> graphNames = ds.listNames();
			if(graphNames!=null){
				while (graphNames.hasNext()) {
				    String graphName = graphNames.next();
				    m_graphsByDataset.put(graphName, ds);
				    sGraphs.add(graphName);
				}
			}
			else{
				m_graphsByDataset.put("NOGRAPHS", ds);
			}
		}
		hash.put(msg.m_request.getSession().getId(), m_graphsByDataset);
		return graphsList;
	}	
	
	static public HashMap<String, Dataset> getGraphsByDataset(String sessionId){
		return hash.get(sessionId);
	}
}
